package com.just_bean.core;

import com.just_bean.core.bean.BaseBean;
import com.just_bean.core.exception.BeanInitException;
import com.just_bean.core.exception.BeanScanException;
import com.just_bean.core.handler.AnnoHandler;
import com.just_bean.core.manager.BeanManager;
import com.just_bean.core.utils.ClassUtils;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;

/**
 * 对外提供接口
 * T get(clz); 根据类获取实例
 * void register(String, BaseBean.clz); 往框架注入bean
 */
public class JustBean {
    // bean实例管理
    private BeanManager beanManager;

    // 注册自定义组件
    public void register(Map<Class<? extends Annotation>, AnnoHandler> handlerMap, Map<Class<? extends Annotation>, Class<? extends BaseBean>> beanClzMap) {
        // bean转换
        this.beanManager = new BeanManager(beanClzMap);
        // 注册注解解析器
        BaseBean.HANDLER_MAP = handlerMap;
    }

    public void scan(Class<?> accessClz) throws BeanInitException, BeanScanException {
        try {
            // 扫描类
            List<Class<?>> list = ClassUtils.all(accessClz);
            this.beanManager.injectClass(list);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            throw new BeanScanException();
        }
    }

    public <T> T get(Class<T> clz, Object... cond) throws Exception {
        return this.beanManager.get(clz, cond);
    }

    public List<? extends BaseBean> listBeanWithAnnotation(Class<? extends Annotation> annoClz) {
        return this.beanManager.listBeanWithAnnotation(annoClz);
    }
}
